
const usersModel = require('../models/users')
const { hash, compare, sign, verify } = require('../utils/tools')
// const randomstring = require("randomstring");

// 验证用户是否是合法用户
const signin = async (req, res, next) => {
  res.set('content-type', 'application/json;charset=utf-8')
  const { username, password } = req.body
  let result = await usersModel.findUser(username)
  if(result) {
    let { password: hash } = result
    if(password) {
      const compareResult = await compare(password, hash)
      if(compareResult) {

        // const sessionId = randomstring.generate();
        // res.set('Set-Cookie', `sessionId=${sessionId};Path=/;HttpOnly`)

        // req.session.username = username
        // console.log(req.session.username)

        const token = sign(username)
        // 自定首部字段一般以x开头
        res.set('X-Access-Token', token)

        res.render('succ', {
          data: JSON.stringify({
            username,
            message: '登录成功！'
          })
        })

      } else {
        res.render('fail', {
          data: JSON.stringify({
            message: '用户名或密码错误。'
          })
        })
      }
    } else {
      res.render('fail', {
        data: JSON.stringify({
          message: '密码不能为空。'
        })
      })
    }
  } else {
    res.render('fail', {
      data: JSON.stringify({
        message: '用户名或密码错误。'
      })
    })
  }
}

// 注册用户
const signup = async (req, res, next) => {
  // res.send('hello');
  res.set('content-type', 'application/json;charset=utf-8')
  const { username, password } = req.body

  // 密码加密
  const bcryptPassword = await hash(password)

  // 判断用户是否存在
  let findResult = await usersModel.findUser(username)
  // null
  if(findResult) {
    res.render('fail', {
      data: JSON.stringify({
        message: '用户名存在。'
      })
    })
  } else {
    // 数据库里没有这个用户，开始添加用户
    let result = await usersModel.signup({ // 异步
      username,
      password: bcryptPassword
    })
    // todo: 1. 存储异步问题，有时间差；2. 用户名查询；3. 密码加密；
    // console.log(result)

    res.render('succ', {
      data: JSON.stringify({
        message: '注册成功！'
      })
    })
  }
}

// 退出登录
const signout = async (req, res, next) => {
  // req.session = null
  res.set('X-Access-Token', '')
  res.render('succ', {
    data: JSON.stringify({
      message: '退出成功！'
    })
  })
}

// 用户列表
const list = async (req, res, next) => {

  res.set('content-type', 'application/json;charset=utf-8')

  const result = await usersModel.findList()
  // console.log(result)

  res.render('succ', {
    data: JSON.stringify(result)
  })
}
// 删除用户
const remove = async (req, res, next) => {
  const { id } = req.body
  res.set('content-type', 'application/json;charset=utf-8')

  let result = await usersModel.remove(id)
  console.log(result)
  if(result && result.deletedCount === 1) {
    res.render('succ', {
      data: JSON.stringify({
        message: '用户删除成功！'
      })
    })
  } else {
    res.render('fail', {
      data: JSON.stringify({
        message: '用户删除失败。'
      })
    })
  }
}

const isAuth = (req, res) => {
  // if (req.session.username) {
  let token = req.get('X-Access-Token')
  try{
    let result = verify(token)
    res.render('succ', {
      data: JSON.stringify({
        username: result.username,
        message: '成功。'
      })
    })
  } catch (e) {
    res.render('fail', {
      data: JSON.stringify({
        message: '失败。'
      })
    })
  }
  // if (req.session.username) {
  //   res.render('succ', {
  //     data: JSON.stringify({
  //       username: req.session.username,
  //       message: '成功。'
  //     })
  //   })
  // } else {
  //   res.render('fail', {
  //     data: JSON.stringify({
  //       message: '失败。'
  //     })
  //   })
  // }
}

exports.signup = signup
exports.list = list
exports.remove = remove
exports.signin = signin
exports.signout = signout
exports.isAuth = isAuth
